package ory

import (
	"context"
	"fmt"

	client "github.com/ory/kratos-client-go"
)

func NewKratos(ctx context.Context, url string) *Kratos {
	configuration := client.NewConfiguration()
	configuration.Servers = []client.ServerConfiguration{
		{
			URL: url,
		},
	}

	return &Kratos{
		ctx:    ctx,
		client: client.NewAPIClient(configuration),
	}
}

type Kratos struct {
	ctx    context.Context
	client *client.APIClient
}

func (r *Kratos) ToSession(cookie string) (*client.Session, error) {
	session, _, err := r.client.FrontendAPI.ToSession(r.ctx).Cookie(fmt.Sprintf("ory_kratos_session=%s", cookie)).Execute()

	return session, err
}
func (r *Kratos) IdentityCreate(user *KratosUser) (*client.Identity, error) {
	body := client.NewCreateIdentityBody("default", map[string]interface{}{
		"email": user.Email,
		"name": map[string]string{
			"first": user.Firstname,
			"last":  user.Lastname,
		},
	})

	identity, _, err := r.client.IdentityAPI.CreateIdentity(r.ctx).CreateIdentityBody(*body).Execute()

	return identity, err
}
func (r *Kratos) IdentityGet(identityId string) (*client.Identity, error) {
	identity, _, err := r.client.IdentityAPI.GetIdentity(r.ctx, identityId).Execute()

	return identity, err
}
func (r *Kratos) IdentityDelete(identityId string) error {
	_, err := r.client.IdentityAPI.DeleteIdentity(r.ctx, identityId).Execute()

	return err
}
